package com.ljj.examisto.ui.dialog

import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.ArrayAdapter
import android.widget.RadioButton
import android.widget.TextView
import android.widget.Toast
import com.ljj.examisto.R
import com.ljj.examisto.ui.base.BaseDialog
import com.ljj.examisto.data.item.NameValueItem
import com.ljj.examisto.data.item.RemindType
import com.ljj.examisto.data.item.Reminder
import com.ljj.examisto.databinding.DialogAddRemindBinding
import com.ljj.examisto.util.RemindOptionProvider
import com.ljj.examisto.util.ToastManager

class AddRemindDialog(
    context: Context,
    private val reminders: List<Reminder>
) : BaseDialog(context, R.style.BottomLeftScaleDialog) {
    interface OnConfirmListener {
        fun onRemindConfirmed(reminder: Reminder)
    }

    private var binding: DialogAddRemindBinding
    private var onConfirmListener: OnConfirmListener? = null
    // 定义提醒选项的数据源
    private val remindOptions: List<NameValueItem> = RemindOptionProvider.remindOptions.toList()

    init {
        setCancelable(true)
        setCanceledOnTouchOutside(true)
        binding = DialogAddRemindBinding.inflate(layoutInflater)
        setContentView(binding.root)
        adjustWindowSize()
        setupTimeOptionsSpinner()
        setupConfirmButton()
    }

    // 自定义回调方法
    fun setOnConfirmListener(listener: OnConfirmListener) {
        this.onConfirmListener = listener
    }

    private fun adjustWindowSize() {
        window?.apply {
            val layoutParams = attributes
            val screenWidth = context.resources.displayMetrics.widthPixels
            layoutParams.width = (screenWidth * 0.8).toInt()
            layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT
            attributes = layoutParams
        }
    }

    private fun setupTimeOptionsSpinner() {
        // 自定义适配器，只显示 name
        val adapter = object : ArrayAdapter<NameValueItem>(
            context,
            android.R.layout.simple_spinner_item,
            remindOptions
        ) {
            override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
                val view = super.getView(position, convertView, parent)
                val textView = view.findViewById<TextView>(android.R.id.text1)
                textView.text = getItem(position)?.name
                // 设置文本颜色以适应当前主题
                textView.setTextColor(context.getColor(R.color.text_color))
                view.alpha = if (ifExistsSameReminder(position)) 0.5f else 1.0f
                return view
            }
            override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
                val view = super.getDropDownView(position, convertView, parent)
                val textView = view.findViewById<TextView>(android.R.id.text1)
                textView.text = getItem(position)?.name
                // 设置下拉项文本颜色和背景色以适应当前主题
                textView.setTextColor(context.getColor(R.color.text_color))
                view.setBackgroundColor(context.getColor(R.color.box))
                view.alpha = if (ifExistsSameReminder(position)) 0.5f else 1.0f
                return view
            }
            override fun isEnabled(position: Int): Boolean {
                return !ifExistsSameReminder(position)
            }
        }
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        binding.spinnerTimeOptions.adapter = adapter
        val defaultPosition = remindOptions.indexOfFirst { !ifExistsSameReminder(remindOptions.indexOf(it)) }
        if (defaultPosition != -1) {
            binding.spinnerTimeOptions.setSelection(defaultPosition)
        }
    }

    private fun setupConfirmButton() {
        binding.btnConfirm.setOnClickListener {
            val radioGroup = binding.rgRemindType
            val selectedItem = binding.spinnerTimeOptions.selectedItem as? NameValueItem
            val selectedValue = selectedItem?.value
            val type = when (radioGroup.findViewById<RadioButton>(radioGroup.checkedRadioButtonId)) {
                binding.rbNotification -> RemindType.NOTIFICATION
                binding.rbAlarm -> RemindType.ALARM
                else -> null
            }
            if (selectedValue == null) {
                ToastManager.interruptedToast(context, "请选择提醒时间", Toast.LENGTH_SHORT)
            } else if (type  == null) {
                ToastManager.interruptedToast(context, "请选择至少一种提醒方式", Toast.LENGTH_SHORT)
            } else {
                // 检查是否已经有时间相同的提醒
                if (reminders.any { it.value == selectedValue }) {
                    ToastManager.interruptedToast(context, "已存在该类型提醒", Toast.LENGTH_SHORT)
                } else {
                    val reminder = Reminder(selectedValue, type)
                    onConfirmListener?.onRemindConfirmed(reminder)
                    dismiss()
                }
            }
        }
    }

    private fun ifExistsSameReminder(position: Int): Boolean {
        return reminders.any { it.value == remindOptions[position].value }
    }
}